package com.koi.validator.valid;

import com.koi.validator.anno.ValidURL;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ･ᴗ･
 * @description [URLValidator-URL校验器]
 */
public class URLValidator implements ConstraintValidator<ValidURL, String> {

    @Override
    public boolean isValid(String urlValue, ConstraintValidatorContext constraintValidatorContext) {
        // 1、如果用户没输入直接返回不校验，因为空的判断交给@NotNull去做就行了
        if (urlValue == null || urlValue.isEmpty()) {
            return true;
        }
        Pattern p = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
        // 2、如果校验通过就返回true，否则返回false;
        Matcher matcher = p.matcher(urlValue);
        return matcher.matches();
    }

    @Override
    public void initialize(ValidURL constraintAnnotation) {

    }

}
